<?php
namespace App\Controllers\Sms;

use App\Controllers\BaseController;
use App\Library\App;
use App\Library\Helper;
use App\Library\Http;
use App\Library\SmsGateway\Adapter as SmsAdapter;
use App\Models\DaredoMo;
use App\Models\HdMoLog;
use App\Models\HdMtReceiptLog;

class ServiceController extends BaseController {

    public function initialize() {
        parent::initialize();
    }

    //-------------------------------------------------------------------------
    // 获取互动上传信息
    //-------------------------------------------------------------------------
    public function moAction() {
        $now       = time();
        $receiveAt = date('Y-m-d H:i:s', $now);
        $config    = App::globalConfig('HDAPI');

        $retMo = file_get_contents('php://input');
        $retMo = str_replace(['encoding="GB2312"', 'encoding="gb2312"'], 'encoding="utf-8"', $retMo);
        $retMo = mb_convert_encoding($retMo, 'UTF-8', 'GB2312');
        //App::Logger()->debug('mo=' . $retMo);

        /*$retMo = '<?xml version="1.0" encoding="utf-8" ?><SBMP_MO_MESSAGE><CONNECT_ID>4648</CONNECT_ID><MO_MESSAGE_ID></MO_MESSAGE_ID><RECEIVE_DATE>20160107</RECEIVE_DATE><RECEIVE_TIME>83026</RECEIVE_TIME><GATEWAY_ID>101</GATEWAY_ID><VALID>1</VALID><CITY_CODE>010</CITY_CODE><CITY_NAME>北京</CITY_NAME><STATE_CODE>010</STATE_CODE><STATE_NAME>北京</STATE_NAME><TP_PID>0</TP_PID><TP_UDHI>0</TP_UDHI><MSISDN>13910868263</MSISDN><MESSAGE_TYPE>8</MESSAGE_TYPE><MESSAGE>美赞臣</MESSAGE><LONG_CODE>7300</LONG_CODE><SERVICE_CODE>9588</SERVICE_CODE></SBMP_MO_MESSAGE>';
        $retMo = '<?xml version="1.0" encoding="UTF-8" ?><SBMP_REPORT_MESSAGE><CONNECT_ID>4648</CONNECT_ID><BUSINESS_CODE>4648MFBZ4648M0000</BUSINESS_CODE><MESSAGE_ID>014648160106115025000005</MESSAGE_ID><MSISDN>18610188165</MSISDN><SUBMIT_TIME></SUBMIT_TIME><DONE_TIME></DONE_TIME><STATUS>DELIVRD</STATUS></SBMP_REPORT_MESSAGE>';*/

        $ret = json_decode(json_encode(simplexml_load_string($retMo, "SimpleXMLElement", LIBXML_NOCDATA)), true);
        if(is_array($ret) && isset($ret['MSISDN']) && isset($ret['MESSAGE'])) {
            //用户上行消息
            $moData  = [
                'mobile'     => !empty($ret['MSISDN']) ? $ret['MSISDN'] : '',
                'message'    => !empty($ret['MESSAGE']) ? $ret['MESSAGE'] : '',
                'msg_id'     => !empty($ret['MO_MESSAGE_ID']) ? $ret['MO_MESSAGE_ID'] : '',
                'long_code'  => !empty($ret['LONG_CODE']) ? $ret['LONG_CODE'] : '',
                'receive_at' => $receiveAt,
                'create_at'  => $receiveAt,
            ];
            $hdMoLog = new HdMoLog();
            $logId   = $hdMoLog->add($moData);

            //美赞臣互动
            if(isset($config[$moData['long_code']])) {
                if(strpos(strtoupper($moData['message']), 'T-E') !== false) {
                    $testConfig = App::globalConfig('HD_API_TEST');
                    $api        = $testConfig[$moData['long_code']];
                    $data       = [
                        'mobile'  => $moData['mobile'],
                        'content' => str_replace(['T-E', 'T-e', 't-E', 't-e'], '', $moData['message']),
                        'time'    => date('YmdHis', $now),
                    ];
                    //App::Logger()->debug('api=' . $api . '?' . http_build_query($data));
                    $retApi = Http::request($api, 'POST', $data);
                    App::Logger()->debug('HD_API_TEST?api=' . $api . '?mobile=' . $data['mobile'] . '&content=' . $data['content'] . 'retApi=' . $retApi);
                    if($retApi != '') {
                        $retApiJson = json_decode($retApi, true);
                        if(is_array($retApiJson) && isset($retApiJson['mobile']) && isset($retApiJson['content']) && $retApiJson['mobile'] == $moData['mobile']) {
                            $mtApiData = [
                                'id'                => $logId,
                                'mt_api_message'    => $retApiJson['content'],
                                'mt_api_receive_at' => Helper::getNow()
                            ];
                            $hdMoLog->edit($mtApiData);
                        }
                    }
                } else {
                    $api    = $config[$moData['long_code']];
                    $data   = [
                        'mobile'  => $moData['mobile'],
                        'content' => $moData['message'],
                        'time'    => date('YmdHis', $now),
                    ];
                    $retApi = Http::request($api, 'POST', $data);
                    //App::Logger()->debug('api=' . $api . '?' . http_build_query($data) . '&retApi=' . $retApi);
                    if($retApi != '') {
                        $retApiJson = json_decode($retApi, true);
                        if(is_array($retApiJson) && isset($retApiJson['mobile']) && isset($retApiJson['content']) && $retApiJson['mobile'] == $moData['mobile']) {
                            $mtApiData = [
                                'id'                => $logId,
                                'mt_api_message'    => $retApiJson['content'],
                                'mt_api_receive_at' => Helper::getNow()
                            ];
                            $hdMoLog->edit($mtApiData);
                        }
                    }
                }
            }
            if(!isset($mtApiData)) {
                if(isset($retApi)) {
                    App::Logger()->debug('long_code=' . $moData['long_code'] . '&mobile=' . $moData['mobile'] . '&content=' . $moData['message'] . '&retApiError=' . $retApi);
                }
                $mtApiData = [
                    'id'                => $logId,
                    'mt_api_message'    => '系统错误，请稍候再试！本条免费，客服电话：010-53358612 回复TD退订【美赞臣】',
                    'mt_api_receive_at' => Helper::getNow()
                ];
                $hdMoLog->edit($mtApiData);
            }

            //调用下行接口
            if(isset($mtApiData['mt_api_message']) && strlen($mtApiData['mt_api_message']) > 1) {
                $api = 'http://4648:wszdwxgs@59.151.7.69/SmbpHttpAgent/SmbpHttpAgent.asmx/SmbppSendUnicodeMessage?bstrMoMessageID=%s&bstrBusinessCode=4648MFBZ4648M0000&bstrLongCode=%s&bstrFeeMsisdn=%s&bstrDesMsisdn=%s&bstrMessageContent=%s&lTpPid=0&lTpUdhi=0&lSendDate=0&lSendTime=0&lExpireDate=0&lExpireTime=0';
                $url = sprintf($api, $moData['msg_id'], $moData['long_code'], $moData['mobile'], $moData['mobile'], urlencode(mb_convert_encoding($mtApiData['mt_api_message'], 'GB2312', 'UTF-8')));
                //App::Logger()->debug('url=' . $url);
                $ret = Http::request($url);
                /*<?xml version="1.0" encoding="utf-8"?><IMessageID xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://wapdm.com/SmbpHttpAgent/"><MessageID>014648160106115025000005</MessageID><Result>0</Result></IMessageID>*/
                //App::Logger()->debug('ret=' . $ret);
                $ret = json_decode(json_encode(simplexml_load_string($ret, "SimpleXMLElement", LIBXML_NOCDATA)), true);
                if(isset($ret['MessageID'])) {
                    $mtData = [
                        'id'        => $logId,
                        'mt_msg_id' => !empty($ret['MessageID']) ? $ret['MessageID'] : '',
                        'mt_status' => (isset($ret['Result']) && is_numeric($ret['Result'])) ? intval($ret['Result']) : 0,
                        'mt_at'     => $receiveAt,
                    ];
                    $hdMoLog->edit($mtData);
                }
            }
        } else if(is_array($ret) && isset($ret['MESSAGE_ID'])) {
            //mt回执消息,提取MESSAGE_ID和STATUS写入hd_mt_receipt_log(receive_at为默认值)
            $receipt        = [
                'msg_id'     => !empty($ret['MESSAGE_ID']) ? $ret['MESSAGE_ID'] : '',
                'status'     => !empty($ret['STATUS']) ? $ret['STATUS'] : '',
                'mobile'     => !empty($ret['MSISDN']) ? $ret['MSISDN'] : '',
                'receive_at' => $receiveAt,
            ];
            $hdMtReceiptLog = new HdMtReceiptLog();
            $hdMtReceiptLog->add($receipt);
            if($receipt['status'] != 'DELIVRD') {
                //通过msg_id抓取信息
                $hdMoLog  = new HdMoLog();
                $retMoLog = $hdMoLog->getByMtMsgId($receipt['msg_id']);
                if($retMoLog !== false) {
                    if(isset($retMoLog['mt_api_message']) && strlen($retMoLog['mt_api_message']) > 0) {
                        $upMtApiMessage = strtoupper($retMoLog['mt_api_message']);
                        if(mb_strpos($upMtApiMessage, '回复TD退订', 0, 'utf-8') === false) {
                            $retMoLog['mt_api_message'] = $retMoLog['mt_api_message'] . '回复TD退订';
                        }
                        if(mb_strpos($upMtApiMessage, '【美赞臣】', 0, 'utf-8') === false) {
                            $retMoLog['mt_api_message'] = $retMoLog['mt_api_message'] . '【美赞臣】';
                        }
                        $mtLength = mb_strlen($retMoLog['mt_api_message'], 'utf-8');
                        if($mtLength <= 70) {
                            $mtFeeCount = 1;
                        } else {
                            $mtFeeCount = ceil($mtLength / 68);
                        }
                        //调用一点通下行接口
                        $adapter = new SmsAdapter();
                        $adapter->loadDriver('yunpian');
                        $retGateway = $adapter->mt($retMoLog['mobile'], $retMoLog['mt_api_message']);
                        $data       = [
                            'mobile'            => $retMoLog['mobile'],
                            'message'           => $retMoLog['message'],
                            'receive_at'        => $retMoLog['receive_at'],
                            'mt_api_message'    => $retMoLog['mt_api_message'],
                            'mt_api_receive_at' => $retMoLog['mt_api_receive_at'],
                            'mt_length'         => $mtLength,
                            'mt_fee_count'      => $mtFeeCount,
                            'mt_status'         => $retGateway['status'],
                            'mt_gateway'        => 'yunpian',
                            'mt_gateway_msg'    => $retGateway['gateway_msg'],
                            'mt_at'             => $retGateway['send_at'],
                            'create_at'         => date('Y-m-d H:i:s')
                        ];
                        $daredoMo   = new DaredoMo();
                        $daredoMo->add($data);
                    }
                }
            }
        } else {
            //nothing
        }
        echo 'OK';
        exit();
    }

    public function daredoAction() {
        $now   = time();
        $retMo = file_get_contents('php://input');
        //$retMo = str_replace(['encoding="GB2312"', 'encoding="gb2312"'], 'encoding="utf-8"', $retMo);
        //$retMo = mb_convert_encoding($retMo, 'UTF-8', 'GB2312');
        //App::Logger()->debug('daredoMo=' . urldecode($retMo));
        parse_str($retMo, $moArray);
        if(is_array($moArray) && isset($moArray['mobs']) && isset($moArray['msg'])) {
            $daredoMo    = new DaredoMo();
            $mobile      = $moArray['mobs'];
            $content     = $moArray['msg'];
            $checkMobile = $daredoMo->isExists($mobile);
            if($checkMobile) {
                //调用BS接口
                if(strpos(strtoupper($content), 'T-E') !== false) {
                    $testConfig = App::globalConfig('HD_API_TEST');
                    $api        = $testConfig['7288'];
                    $data       = [
                        'mobile'  => $mobile,
                        'content' => str_replace(['T-E', 'T-e', 't-E', 't-e'], '', $content),
                        'time'    => date('YmdHis', $now),
                    ];
                    //App::Logger()->debug('api=' . $api . '?' . http_build_query($data));
                    $retApi = Http::request($api, 'POST', $data);
                    App::Logger()->debug('HD_API_TEST?api=' . $api . '?mobile=' . $data['mobile'] . '&content=' . $data['content'] . 'retApi=' . $retApi);
                } else {
                    $config = App::globalConfig('HDAPI');
                    $api    = $config['7288'];
                    $data   = [
                        'mobile'  => $mobile,
                        'content' => $content,
                        'time'    => date('YmdHis', $now),
                    ];
                    $retApi = Http::request($api, 'POST', $data);
                }
                if($retApi != '') {
                    $retApiJson = json_decode($retApi, true);
                    if(is_array($retApiJson) && isset($retApiJson['mobile']) && isset($retApiJson['mobile'])) {
                        $mtApiData = [
                            'mt_api_message'    => $retApiJson['content'],
                            'mt_api_receive_at' => Helper::getNow()
                        ];
                    }
                    if(!isset($mtApiData)) {
                        $mtApiData = [
                            'mt_api_message'    => '系统错误，请稍候再试！本条免费，客服电话：010-53358612 回复TD退订【美赞臣】',
                            'mt_api_receive_at' => Helper::getNow()
                        ];
                    }
                    if(isset($mtApiData['mt_api_message']) && strlen($mtApiData['mt_api_message']) > 0) {
                        $upMtApiMessage = strtoupper($mtApiData['mt_api_message']);
                        if(mb_strpos($upMtApiMessage, '回复TD退订', 0, 'utf-8') === false) {
                            $mtApiData['mt_api_message'] = $mtApiData['mt_api_message'] . '回复TD退订';
                        }
                        if(mb_strpos($upMtApiMessage, '【美赞臣】', 0, 'utf-8') === false) {
                            $mtApiData['mt_api_message'] = $mtApiData['mt_api_message'] . '【美赞臣】';
                        }
                        $mtLength = mb_strlen($mtApiData['mt_api_message'], 'utf-8');
                        if($mtLength <= 70) {
                            $mtFeeCount = 1;
                        } else {
                            $mtFeeCount = ceil($mtLength / 68);
                        }
                        //调用一点通下行接口
                        $adapter = new SmsAdapter();
                        $adapter->loadDriver('daredo');
                        $retGateway = $adapter->mt($mobile, $mtApiData['mt_api_message']);
                        $data       = [
                            'mobile'            => $mobile,
                            'message'           => $content,
                            'receive_at'        => date('Y-m-d H:i:s', $now),
                            'mt_api_message'    => $mtApiData['mt_api_message'],
                            'mt_api_receive_at' => $mtApiData['mt_api_receive_at'],
                            'mt_length'         => $mtLength,
                            'mt_fee_count'      => $mtFeeCount,
                            'mt_status'         => $retGateway['status'],
                            'mt_gateway'        => 'daredo',
                            'mt_gateway_msg'    => $retGateway['gateway_msg'],
                            'mt_at'             => $retGateway['send_at'],
                            'create_at'         => date('Y-m-d H:i:s')
                        ];
                        $daredoMo->add($data);
                    } else {
                        $data = [
                            'mobile'            => $mobile,
                            'message'           => $content,
                            'receive_at'        => date('Y-m-d H:i:s', $now),
                            'mt_api_message'    => $mtApiData['mt_api_message'],
                            'mt_api_receive_at' => $mtApiData['mt_api_receive_at'],
                            'mt_length'         => 0,
                            'mt_fee_count'      => 0,
                            'mt_gateway'        => 'daredo',
                            'create_at'         => date('Y-m-d H:i:s')
                        ];
                        $daredoMo->add($data);
                    }
                }
            }
        }
    }

    public function yunpianAction() {
        $now   = time();
        $retMo = file_get_contents('php://input');
        //App::Logger()->debug(urldecode($retMo));
        //sms_reply=%257B%2522id%2522%253A%252287c32cfaa7c24bf79914d0552f46da3e%2522%252C%2522mobile%2522%253A%252218782926605%2522%252C%2522text%2522%253A%2522%25E6%2584%2589%25E5%25BF%25AB%2522%252C%2522reply_time%2522%253A%25222016-03-04%2B15%253A29%253A35%2522%252C%2522extend%2522%253A%2522%2522%252C%2522base_extend%2522%253A%2522282088%2522%252C%2522_sign%2522%253A%2522bf323365d175c0c89062e626dd0edd0d%2522%257D
        if(strpos($retMo, 'sms_reply=') === false) {
            App::Logger()->debug($retMo);
            echo '0';
            exit();
        }
        $retMo = substr($retMo, 10);
        $retMo = urldecode(urldecode($retMo));
        //App::Logger()->debug($retMo);
        $moArray = json_decode($retMo, true);
        if(is_array($moArray) && isset($moArray['mobile']) && isset($moArray['text'])) {
            $daredoMo    = new DaredoMo();
            $mobile      = $moArray['mobile'];
            $content     = $moArray['text'];
            $checkMobile = $daredoMo->isExists($mobile);
            if($checkMobile) {
                //调用BS接口
                if(strpos(strtoupper($content), 'T-E') !== false) {
                    $testConfig = App::globalConfig('HD_API_TEST');
                    $api        = $testConfig['7288'];
                    $data       = [
                        'mobile'  => $mobile,
                        'content' => str_replace(['T-E', 'T-e', 't-E', 't-e'], '', $content),
                        'time'    => date('YmdHis', $now),
                    ];
                    //App::Logger()->debug('api=' . $api . '?' . http_build_query($data));
                    $retApi = Http::request($api, 'POST', $data);
                    App::Logger()->debug('HD_API_TEST?api=' . $api . '?mobile=' . $data['mobile'] . '&content=' . $data['content'] . 'retApi=' . $retApi);
                } else {
                    $config = App::globalConfig('HDAPI');
                    $api    = $config['7288'];
                    $data   = [
                        'mobile'  => $mobile,
                        'content' => $content,
                        'time'    => date('YmdHis', $now),
                    ];
                    $retApi = Http::request($api, 'POST', $data);
                }
                if($retApi != '') {
                    $retApiJson = json_decode($retApi, true);
                    if(is_array($retApiJson) && isset($retApiJson['mobile']) && isset($retApiJson['mobile'])) {
                        $mtApiData = [
                            'mt_api_message'    => $retApiJson['content'],
                            'mt_api_receive_at' => Helper::getNow()
                        ];
                    }
                    if(!isset($mtApiData)) {
                        $mtApiData = [
                            'mt_api_message'    => '系统错误，请稍候再试！本条免费，客服电话：010-53358612 回复TD退订【美赞臣】',
                            'mt_api_receive_at' => Helper::getNow()
                        ];
                    }
                    if(isset($mtApiData['mt_api_message']) && strlen($mtApiData['mt_api_message']) > 0) {
                        $upMtApiMessage = strtoupper($mtApiData['mt_api_message']);
                        if(mb_strpos($upMtApiMessage, '回复TD退订', 0, 'utf-8') === false) {
                            $mtApiData['mt_api_message'] = $mtApiData['mt_api_message'] . '回复TD退订';
                        }
                        if(mb_strpos($upMtApiMessage, '【美赞臣】', 0, 'utf-8') === false) {
                            $mtApiData['mt_api_message'] = $mtApiData['mt_api_message'] . '【美赞臣】';
                        }
                        $mtLength = mb_strlen($mtApiData['mt_api_message'], 'utf-8');
                        if($mtLength <= 70) {
                            $mtFeeCount = 1;
                        } else {
                            $mtFeeCount = ceil($mtLength / 68);
                        }
                        //调用一点通下行接口
                        $adapter = new SmsAdapter();
                        $adapter->loadDriver('yunpian');
                        $retGateway = $adapter->mt($mobile, $mtApiData['mt_api_message']);
                        $data       = [
                            'mobile'            => $mobile,
                            'message'           => $content,
                            'receive_at'        => date('Y-m-d H:i:s', $now),
                            'mt_api_message'    => $mtApiData['mt_api_message'],
                            'mt_api_receive_at' => $mtApiData['mt_api_receive_at'],
                            'mt_length'         => $mtLength,
                            'mt_fee_count'      => $mtFeeCount,
                            'mt_status'         => $retGateway['status'],
                            'mt_gateway'        => 'yunpian',
                            'mt_gateway_msg'    => $retGateway['gateway_msg'],
                            'mt_at'             => $retGateway['send_at'],
                            'create_at'         => date('Y-m-d H:i:s')
                        ];
                        $daredoMo->add($data);
                    } else {
                        $data = [
                            'mobile'            => $mobile,
                            'message'           => $content,
                            'receive_at'        => date('Y-m-d H:i:s', $now),
                            'mt_api_message'    => $mtApiData['mt_api_message'],
                            'mt_api_receive_at' => $mtApiData['mt_api_receive_at'],
                            'mt_length'         => 0,
                            'mt_fee_count'      => 0,
                            'mt_gateway'        => 'yunpian',
                            'create_at'         => date('Y-m-d H:i:s')
                        ];
                        $daredoMo->add($data);
                    }
                }
            }
        }
        echo '0';
        exit();
    }

    public function testAction() {
        $hdMoLog  = new HdMoLog();
        $mtMsgId  = '014648160106174703000008';
        $retMoLog = $hdMoLog->getByMtMsgId($mtMsgId);
        if($retMoLog !== false) {
            if(isset($retMoLog['mt_api_message']) && strlen($retMoLog['mt_api_message']) > 0) {
                $upMtApiMessage = strtoupper($retMoLog['mt_api_message']);
                if(mb_strpos($upMtApiMessage, '回复TD退订', 0, 'utf-8') === false) {
                    $retMoLog['mt_api_message'] = $retMoLog['mt_api_message'] . '回复TD退订';
                }
                if(mb_strpos($upMtApiMessage, '【美赞臣】', 0, 'utf-8') === false) {
                    $retMoLog['mt_api_message'] = $retMoLog['mt_api_message'] . '【美赞臣】';
                }
                //调用一点通下行接口
                $adapter = new SmsAdapter();
                $adapter->loadDriver('daredo');
                $retGateway = $adapter->mt($retMoLog['mobile'], $retMoLog['mt_api_message']);
                $data       = [
                    'mobile'            => $retMoLog['mobile'],
                    'message'           => $retMoLog['message'],
                    'receive_at'        => $retMoLog['receive_at'],
                    'mt_api_message'    => $retMoLog['mt_api_message'],
                    'mt_api_receive_at' => $retMoLog['mt_api_receive_at'],
                    'mt_status'         => $retGateway['status'],
                    'mt_gateway_msg'    => $retGateway['gateway_msg'],
                    'mt_at'             => $retGateway['send_at'],
                    'create_at'         => date('Y-m-d H:i:s')
                ];
                $daredoMo   = new DaredoMo();
                $daredoMo->add($data);
            }
        }
    }
}